<template>
    <div class="coin-state d-flex align-center">
        <div class="coin-type d-flex align-center user-none">
            <img alt="chainingview" :src="getImg(kline.curCoin?.baseCurrency)" class="c-img seo-font" @click="onDetail" />
            <!-- <v-menu class="h-menu" transition="slide-y-reverse-transition" offset="0" start open-on-hover v-model="iptShow"> -->
            <v-menu class="h-menu" transition="slide-y-reverse-transition" offset="0" start open-on-hover v-model="iptShow">
                <template v-slot:activator="{ props }">
                    <div class="coin-dei" v-bind="props">
                        <span class="c-title-6 c-name">{{ kline.curCoin?.symbol }}</span>
                        <div class="j-bt">
                            <span class="iconfont icon-xiajiantou" @click.stop="iptShow = !iptShow"></span>
                        </div>
                    </div>
                </template>
                <v-list class="muns user-none">
                    <div @click.stop>
                        <TableCoin  :close-ipt="() => (iptShow = false)"></TableCoin>
                    </div>
                </v-list>
            </v-menu>
        </div>
        <div class="coin-table">
            <v-row>
                <v-col>
                    <div class="Change">
                        <div class="coin-price price_" :class="{ up: isUp }">
                            {{ numberWithCommas4(day.c) }}
                            <!-- {{ day.c }} -->

                        </div>
                    </div>
                </v-col>
                <v-col>
                    <div class="tip1" @click="console.log(kline.curCoin)">
                        <!-- 24H涨跌 -->
                        {{ $t("message.CoinState.a") }}
                    </div>
                    <div class="tip2" :style="{ color: (Number(day.p) > 0 ? '#0dcb81' : '#ff0000'), width: '80px' }">{{
                        day.p
                    }} {{ day.P }}%</div>
                </v-col>
                <v-col>
                    <div class="tip1">
                        <!-- 24H最高 -->
                        {{ $t("message.CoinState.b") }}
                    </div>
                    <div class="tip2">
                        {{ numberWithCommas2(day.h) }}
                        <!-- {{ day.h }} -->
                    </div>
                </v-col>
                <v-col>
                    <div class="tip1">
                        <!-- 24H最低 -->
                        {{ $t("message.CoinState.c") }}
                    </div>
                    <div class="tip2">
                        {{ numberWithCommas2(day.l) }}
                        <!-- {{ day.l }} -->

                    </div>
                </v-col>
                <v-col>
                    <div class="tip1">
                        <!-- 24H成交量(BTC) -->
                        {{ getCoinName1($t("message.CoinState.d")) }}
                    </div>
                    <div class="tip2">{{ numberWithCommas(day.v) }}</div>
                </v-col>
                <v-col>
                    <div class="tip1">
                        <!-- 24H成交量(USDT) -->
                        <!-- {{ $t('message.CoinState.e') }} -->
                        {{ getCoinName2($t("message.CoinState.w")) }}
                    </div>
                    <div class="tip2">{{ numberWithCommas(day.q) }}</div>
                </v-col>
                <!-- <v-col>
                    <div class="tip1">
                        合约持仓量
                    </div>
                    <div class="tip2">{{ day.n }}</div>
                </v-col> -->
            </v-row>

        </div>
        <div class="spaces"></div>
        <!-- <div class="coin-time">
            <v-menu class="header" transition="slide-y-reverse-transition" color="#000" origin="start">
                <template v-slot:activator="{ props }">
                    <div class="j-drop" v-bind="props">
                        <span class="j-tip1">{{ time }}</span>
                        <span class="iconfont icon-sanjiaoxing"></span>
                    </div>
                </template>
                <v-list :width="120" color="#000">
                    <v-list-item v-for="item in maps" :key="item.name" @click.stop="onChooseTime(item)">
                        <v-list-item-title class="d-flex align-center justify-space-between fline">
                            <span class="d-tip1">{{ item.type == 0 ? "Tick" : item.description }}</span>
                        </v-list-item-title>
                    </v-list-item>
                </v-list>
            </v-menu>
        </div> -->
        <!-- <JLoading v-if="kline.headerLoding" /> -->

    </div>
</template>

<script lang="ts" setup>
import {
    Bus,
    CHART_CHAIN_SUBSCRIBE,
    CHART_KLINE_SUBSCRIBE,
    CHART_KLINE_SUBSCRIBE_TIME,
    CHART_KLINE__ITEM,
    DAY_STATE,
    INDICATOR_FUNDS,
    INDICATOR_MA,
    INDICATOR_TREND,
    INDICATOR_VOL,
    INDICATOR_WAVE,
    KLINE_RESET,
    KLINE_RESET_PRICE
} from "@/connetion/Bus";
import { useKline } from "@/stores/kline";
import { computed, ref, onMounted, reactive } from "vue";
import JInput from "@/components/j-input/index.vue";
import JCheckbox from "@/components/j-checkbox/index.vue";
import { useRouter } from "vue-router";
import { useSignal } from "@/stores/signal";
import { useCore } from "@/hooks/useCore";
import { useTokens } from "@/stores/tokens";
import i18n from "@/locals";
import { useIndicator } from "@/stores/indicator";
import TableCoin from "./tableCoin.vue";
import { fixNumber, numberWithCommas, numberWithCommasTwo } from "@/comm/format";
import { URL_COIN_STATE } from "@/comm/api";
import { get } from "@/comm/request";
import { VAlert } from "vuetify/lib/components/index.mjs";
import JLoading from "@/components/j-loding/index.vue";

//用来隐藏
const iptShow = ref(false);

const coinImg = ref("/vite.svg");
const kline = useKline();
const search = ref("");
const router = useRouter();
const signal = useSignal();
const core = useCore();
const tokens = useTokens();
const indicator = useIndicator();
// const curItem = ref<any>(null);
const getImg = (str: string) => {
    return tokens.getImg(str);
};

const formatZero = (n: any) => {
    // return fixNumber(n, kline.curCoin?.priceDisplayDp || 2);
    return formatPrecision(n, kline.priceLen)
};

function formatPrecision(value: any, precision: number) {
    var v = +value;
    return v.toFixed(precision !== null && precision !== void 0 ? precision : 2);
}

const numberWithCommas2 = (n: any) => {
    // console.log(n)
    // return n
    let p = 3;
    if (kline.curCoin?.priceDisplayDp) {
        p = kline.curCoin?.priceDisplayDp + 1;
        // console.log(kline)
    }
    return numberWithCommasTwo(n, p);
    // return fixNumber(n, p)
}

let fix = 2;
const numberWithCommas4 = (n: number) => {
    return n
    let str = n.toString()
    if (str.includes(".")) {
        let ary = str.split(".");
        return ary[0] + "." + (ary[1] + fixZero(fix)).substring(0, fix);
    }
    return n + "." + fixZero(fix);
}

const fixZero = (n: number) => {
    return new Array(n).fill(0).join("");
}

const numberWithCommas3 = (n: any) => {
    // let p = 3;
    // if(kline.curCoin?.priceDisplayDp){
    //     p = kline.curCoin?.priceDisplayDp;
    // }

    // sizeDisplayDp priceDisplayDp
    // return fixNumber(n, p);
    return fixNumber(n, kline.priceLen);
}

const time = computed(() => {
    if (!kline.curInterval) return "";
    if (kline.curInterval.type == 0) return "Tick";
    return kline.curInterval.description;
});

const onDetail = () => {
    kline.saveLastData();
    // router.push({ name: "coin", params: { id: kline.curCoin.symbol } })
    // router.push({path: "/coinDetail", query: {coin: kline.curCoin.symbol}});
    window.open("/coin/" + kline.curCoin.symbol);
};

const coins = computed(() => {
    const key = search.value.toLowerCase();
    if (kline.map && kline.map.length) {
        if (!key) {
            return kline.map;
        }
        return kline.map.filter(i => i.symbol.toLowerCase().includes(key));
    }
    return [];
});

const onChooseCoin = async (item: any) => {
    // kline.changeCurCoin(item);
    console.log("##jsz 切换", item);
    await core.switchCoin(item);
    Bus.emit(CHART_KLINE_SUBSCRIBE, kline.param);
    Bus.emit(CHART_CHAIN_SUBSCRIBE, item.tokenAddress);
};


const day = reactive({
    h: 0,
    l: 0,
    v: 0,
    n: 0,
    c: 0,
    P: 0,
    p: 0,
    q: 0
});

const lastPrice = ref(0);
const isUp = ref(false);
const idxes = ref([
    { title: i18n.global.t("message.CoinState.idxes.a"), choose: false, name: INDICATOR_WAVE },
    { title: i18n.global.t("message.CoinState.idxes.b"), choose: false, name: INDICATOR_FUNDS },
    { title: i18n.global.t("message.CoinState.idxes.c"), choose: false, name: INDICATOR_TREND },
    { title: i18n.global.t("message.CoinState.idxes.d"), choose: false, name: INDICATOR_MA },
    { title: i18n.global.t("message.CoinState.idxes.e"), choose: false, name: INDICATOR_VOL }
]);
const onChooseIdx = (item: any) => {
    item.selected = !item.selected;
    // item.choose = !item.choose;
    // Bus.emit(item.name, item.choose);
    // console.log(item);
    // if(kline.curInterval.type == 0){
    //     console.log("不是K线");
    //     return;
    // }
};

onMounted(() => {
    // let name = kline.curCoin.symbol;
    Bus.on(DAY_STATE, (res: any) => {
        // console.log("DAY_STATE", res);
        if (kline.curCoin && res.s == kline.curCoin.symbol) {
            // isUp.value = res.c >= lastPrice.value;
            // lastPrice.value = res.c;
            day.h = res.h;
            day.l = res.l;
            day.v = res.v;
            day.n = res.n;
            // day.c = res.c;
            day.p = res.p;
            day.P = res.P;
            day.q = res.q;
        }
        // let item = kline.map.find(i => i.symbol == res.s);
        // if (item) {
        //     item.priceChangePercent = res.P; //涨跌幅
        //     item.lastPrice = res.c; //最新价
        //     item.quoteVolume = res.q;
        // }
    });
    Bus.on(CHART_KLINE__ITEM, (val: any) => {
        // console.log("item---", JSON.stringify(val));
        // isUp.value = val.open
        isUp.value = val.close >= lastPrice.value;
        lastPrice.value = val.close;
        day.c = val.close;
        document.title = kline.curCoin.symbol + " " + val.close + " | ChainingView";
    })

    Bus.on(KLINE_RESET, () => {
        let item: any = kline.list.slice(-1);
        if (item && item[0]) {
            day.c = item[0].close;
        }
        console.log("切换获取价格", day.c);
        lastStateChange();
        //@ts-ignore
        kline.headerLoding = false
    });

});

const lastStateChange = () => {
    get(URL_COIN_STATE, { key: kline.curCoin.symbol }).then((res: any) => {
        let obj = res.data;
        if (!obj) return;
        fix = getFixedNum(obj.o);
        day.c = obj.c;
        day.h = obj.h;
        day.l = obj.l;
        day.v = obj.v;
        day.n = obj.n;
        day.c = obj.c;
        day.P = obj.P;
        day.p = obj.p;
        day.q = obj.q;
        Bus.emit(KLINE_RESET_PRICE);
    })
}

const getFixedNum = (n: number) => {
    let ary = n.toString().split(".");
    if (ary.length == 2) {
        let t = ary[1].length;
        return Math.max(2, t);
    }
    return 2;
};

const getCoinName1 = (str: string) => {
    if (!kline.curCoin) return str;
    return str.replace("$", kline.curCoin.baseCurrency);
};

const getCoinName2 = (str: string) => {
    if (!kline.curCoin) return str;
    return str.replace("$", kline.curCoin.quoteCurrency);
};
</script>

<style lang="less" scoped>
@import url("./index.less");
</style>
